using B.S.NewMedical.Api.Write.Application.Command.ContentManagement.Hospital;
using B.S.NewMedical.Api.Write.Common;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;

namespace B.S.NewMedical.Api.Write.Application.Handler.ContentManagement.Hospital
{
    /// <summary>
    /// 删除医院命令处理器
    /// </summary>
    public class DeleteHospitalCommandHandler : IRequestHandler<DeleteHospitalCommand, BatchDeleteResult>
    {
        private readonly IBaseRepository<HospitalModel> _hospitalRepository;

        public DeleteHospitalCommandHandler(IBaseRepository<HospitalModel> hospitalRepository)
        {
            _hospitalRepository = hospitalRepository ?? throw new ArgumentNullException(nameof(hospitalRepository));
        }

        /// <summary>
        /// 处理批量删除医院命令
        /// </summary>
        /// <param name="request">批量删除医院命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>批量删除结果</returns>
        public async Task<BatchDeleteResult> Handle(DeleteHospitalCommand request, CancellationToken cancellationToken)
        {
            var result = new BatchDeleteResult();
            var successIds = new List<int>();
            var failedIds = new List<int>();

            foreach (var id in request.Ids)
            {
                try
                {
                    // 查找要删除的医院
                    var hospital = await _hospitalRepository.GetValue(id);
                    if (hospital != null)
                    {
                        // 软删除：设置删除状态和更新时间
                        hospital.IsDeleted = true;
                        hospital.UpdateTime = DateTime.Now;
                        hospital.UpdatePeople = request.UpdatePeople;

                        await _hospitalRepository.UpdateAsync(hospital);
                        successIds.Add(id);
                        result.SuccessCount++;
                    }
                    else
                    {
                        failedIds.Add(id);
                        result.FailCount++;
                    }
                }
                catch (Exception)
                {
                    failedIds.Add(id);
                    result.FailCount++;
                }
            }

            result.FailedIds = failedIds;
            result.Success = result.FailCount == 0;

            if (result.Success)
            {
                result.Message = $"成功删除 {result.SuccessCount} 个医院";
            }
            else
            {
                result.Message = $"成功删除 {result.SuccessCount} 个医院，失败 {result.FailCount} 个医院";
            }

            return result;
        }
    }
}